package com.intelligentmeterreadingsys.report.activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.intelligentmeterreadingsys.R;
import com.intelligentmeterreadingsys.httpserver.RequestUrl;
import com.intelligentmeterreadingsys.httpserver.UploadHttpClient;
import com.intelligentmeterreadingsys.povo.EngineeringOrderPoVo;
import com.intelligentmeterreadingsys.povo.TypePoVo;
import com.intelligentmeterreadingsys.report.db.ReportDao;
import com.intelligentmeterreadingsys.util.DateUtil;
import com.intelligentmeterreadingsys.util.FileNameUtil;
import com.intelligentmeterreadingsys.util.SafetyExitUtil;
import com.intelligentmeterreadingsys.util.SharedPreferenceUtil;
import com.intelligentmeterreadingsys.util.TipHelper;

import dbhelper.DbTableName;
import dbhelper.XmlNameHelper;

public class OrderOtherActivity extends Activity implements OnClickListener,
		BDLocationListener {
	private static final int REQUEST_CODE_TAKE_VIDEO = 2;
	private static final int REQUEST_CODE_TAKE_IMAGE = 1;
	private static final int REQUEST_CODE_TAKE_SOUND = 3;
	private final static int DIALOG = 1;
	public static final int ITEM0 = Menu.FIRST;// 系统值
	public ProgressDialog pd;
	public SafetyExitUtil safe = null;
	public int OrderID = 0;
	public ArrayList<String> imagepath;
	public String videopath;
	public boolean isupload = false;
	public String soundpath;
	public String type = "无";
	public Button button1;// 保存
	public Button button2;// 修改
	public Button button3;// 上传
	public EditText edit1;// 名称
	public EditText edit2;// 描述
	public Spinner spinner;// 类型
	public Button button4;// 定位
	public TextView textview1;// 经度
	public TextView textview2;// 纬度
	public LocationClient client;
	public Double latitude = 0.0;// 维度
	public Double longitude = 0.0;// 径度
	public SharedPreferenceUtil sp;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.order_ordinary);
		sp = new SharedPreferenceUtil(this);
		initlocation();
		init();
	}

	public void init() {
		spinner = (Spinner) findViewById(R.id.ordinary_type);
		edit1 = (EditText) findViewById(R.id.ordinary_ordername);
		edit2 = (EditText) findViewById(R.id.ordinary_desc);
		button1 = (Button) findViewById(R.id.ordinary_save);
		button2 = (Button) findViewById(R.id.ordinary_modify);
		button3 = (Button) findViewById(R.id.ordinary_upload);
		button4 = (Button) findViewById(R.id.ordinary_location);
		textview1 = (TextView) findViewById(R.id.ordinary_textView4);
		textview2 = (TextView) findViewById(R.id.ordinary_textView5);
		button4.setOnClickListener(this);
		button1.setOnClickListener(this);
		button2.setOnClickListener(this);
		button3.setOnClickListener(this);
		// 选择工程类型监听器
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				type = arg0.getItemAtPosition(arg2).toString();
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				type = "无";

			}
		});

		ReportDao dao = new ReportDao(this);

		List<TypePoVo> list = dao.queryOrderType();
		String date[] = null;
		if (list != null && list.size() > 0) {
			date = new String[list.size() + 1];
			date[0] = "请选择";
			for (int i = 0; i < list.size(); i++) {
				date[i + 1] = list.get(i).getName();
			}
		} else {
			date = new String[] { "请选择" };
		}
		dao.close();
		ArrayAdapter<String> ada = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, date);// 放数据
		ada.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(ada);

	}

	@Override
	public void onClick(View v) {
		if (v.getId() == button3.getId()) {

			if (OrderID < 1) {
				Toast.makeText(this, "还没添加工程单呢", 1000).show();
				return;
			}
			pd = new ProgressDialog(this);
			pd.setMessage("上传中.....");
			pd.show();
			new Thread() {

				@Override
				public void run() {
					ReportDao dao = new ReportDao(OrderOtherActivity.this);
					EngineeringOrderPoVo e = dao.queryUpload(OrderID + "").get(
							0);

					dao.close();
					Map<String, String> map1 = new HashMap<String, String>();
					Map<String, String> map3 = new HashMap<String, String>();
					map3.put("desc", e.getDesc());
					map3.put("typeid", e.getTypenumber());
					map3.put("waternumber", e.getWaternumber());
					map3.put("name", e.getName());
					map3.put("latitude", e.getLatitude() + "");
					map3.put("longitude", e.getLongitude() + "");
					Map<File, String> map2 = new HashMap<File, String>();
					SharedPreferenceUtil sh = new SharedPreferenceUtil(
							OrderOtherActivity.this);
					map3.put("imsi", sh.getValue(XmlNameHelper.IMSI));
					List<String> img = e.getImagepath();
					for (int i = 0; i < img.size(); i++) {
						if (img.get(i) != null) {
							File file = new File(img.get(i));

							if (file.exists()) {
								map1.put(file.getName(), "imagename");
								map2.put(file, "imagepath");
							}

						}

					}
					if (e.getSoundpath() != null) {
						File file = new File(e.getSoundpath());
						if (file.exists()) {
							map1.put(file.getName(), "soundname");
							map2.put(file, "soundpath");
						}
					}
					if (e.getVideopath() != null) {
						File file = new File(e.getVideopath());
						if (file.exists()) {
							map1.put(file.getName(), "videoname");
							map2.put(file, "videopath");
						}
					}
					RequestUrl r = new RequestUrl(OrderOtherActivity.this);
					String url = r.getUrl(RequestUrl.UploadOrder);
					System.out.println(url);
					String respon = UploadHttpClient.uploadSubmit(url, map1,
							map2, map3);

					if (respon.equals("error")) {
						Message msg = myHandler.obtainMessage();
						msg.what = 1;
						myHandler.sendMessage(msg);
					} else {
						try {
							JSONObject json = new JSONObject(respon);
							String message = json.getString("message");
							if (message.equals("yes")) {
								Message msg = myHandler.obtainMessage();
								msg.what = 2;
								myHandler.sendMessage(msg);
							} else {
								Message msg = myHandler.obtainMessage();
								msg.what = 3;
								myHandler.sendMessage(msg);
							}
						} catch (JSONException e1) {
							Message msg = myHandler.obtainMessage();
							msg.what = 3;
							myHandler.sendMessage(msg);
						}

					}
				}

			}.start();

		} else if (button2.getId() == v.getId()) {

			if (OrderID < 1) {
				Toast.makeText(this, "还没添加工程单呢", 1000).show();
				return;
			}
			if (isupload) {
				Toast.makeText(this, "已经上传的工程单不能修改", 1000).show();
				return;
			}
			boolean b = modify();
			if (b) {
				Toast.makeText(this, "修改成功", 1000).show();
			} else {
				Toast.makeText(this, "修改失败", 1000).show();
			}

		} else if (button1.getId() == v.getId()) {

			System.out.println("保存");
			if (type.equals("无")) {
				Toast.makeText(this, "请选择工程单类型", 1000).show();
				return;
			}
			if (imagepath != null && imagepath.size() > 0) {
				showDialog(DIALOG + 1);
			} else {
				Toast.makeText(this, "这种情况必须拍照", 1000).show();
				return;
			}

		} else if (v.getId() == button4.getId()) {
			pd = new ProgressDialog(this);
			pd.setMessage("定位中....");
			pd.show();
			client.start();
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		menu.add(0, ITEM0 + 1, 0, "拍照");
		menu.add(0, ITEM0 + 2, 0, "录视频");
		menu.add(0, ITEM0 + 3, 0, "录音");

		menu.findItem(ITEM0 + 1);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {

		case ITEM0 + 1:

			Bundle bundle = new Bundle();

			bundle.putString("otherid", OrderID + "");
			bundle.putString("status", "1");
			bundle.putString("classname", "OrderOtherActivity");
			Intent intent = new Intent(OrderOtherActivity.this,
					OrderImageActivity.class);
			intent.putExtras(bundle);
			startActivityForResult(intent, REQUEST_CODE_TAKE_IMAGE);
			break;
		case ITEM0 + 2:
			videoMethod();
			break;
		case ITEM0 + 3:
			System.out.println("录音");
			soundRecorderMethod();
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	// 拍摄视频
	private void videoMethod() {
		Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
		FileNameUtil f = new FileNameUtil(this);
		videopath = f.videopath();
		String fileName = new SimpleDateFormat("yyyyMMddHHmmss")
				.format(new Date()) + ".avi";
		File out = new File(videopath);
		out = new File(videopath, fileName);
		Uri uri = Uri.fromFile(out);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
		intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
		startActivityForResult(intent, REQUEST_CODE_TAKE_VIDEO);
	}

	/**
	 * 发送短息
	 */
	public void sendMSM(String number, String name) {
		Uri smsToUri = Uri.parse("smsto:" + number);
		Intent sendIntent = new Intent(Intent.ACTION_VIEW, smsToUri);

		sendIntent.putExtra("sms_body", "尊敬的" + name + "用户:你的水表已绑定RFID卡");

		startActivity(sendIntent);
		System.out.println("发短息");
	}

	// 录音功能
	private void soundRecorderMethod() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.setType("audio/*");

		startActivityForResult(intent, REQUEST_CODE_TAKE_SOUND);
	}

	// 执行回调函数
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_CODE_TAKE_VIDEO) {
			System.out.println("返回视频");
			if (resultCode == RESULT_OK) {
				videopath = data.getData().toString().substring(7);
				System.out.println(videopath);
			}
		} else if (requestCode == REQUEST_CODE_TAKE_IMAGE) {
			if (resultCode == RESULT_OK) {
				imagepath = data.getStringArrayListExtra("imgpath");
			}
		} else if (requestCode == REQUEST_CODE_TAKE_SOUND) {
			if (resultCode == RESULT_OK) {
				Uri uriVideo = data.getData();
				Cursor cursor = this.getContentResolver().query(uriVideo, null,
						null, null, null);
				if (cursor.moveToNext()) {
					String strVideoPath = cursor.getString(cursor
							.getColumnIndex("_data"));
					FileInputStream fin = null;
					FileOutputStream fout = null;

					File file = new File(strVideoPath);

					try {
						fin = new FileInputStream(file);

						FileNameUtil f = new FileNameUtil(this);
						soundpath = f.soundpath();
						if (soundpath == null) {
							Toast.makeText(OrderOtherActivity.this, "SD卡不可用",
									Toast.LENGTH_LONG).show();
							return;
						}
						String fileName = new SimpleDateFormat("yyyyMMddHHmmss")
								.format(new Date()) + ".amr";
						soundpath = soundpath + "/" + fileName;
						System.out.println(soundpath);
						fout = new FileOutputStream(soundpath);

						byte[] buffer = new byte[1024];
						int bytesRead;
						while ((bytesRead = fin.read(buffer)) > 0) {

							fout.write(buffer, 0, bytesRead);
						}
						fin.close();
						fout.close();
					} catch (FileNotFoundException e) {

						e.printStackTrace();
					} catch (IOException e) {

						e.printStackTrace();
					} finally {
						file.delete();
					}

				}
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog = null;
		switch (id) {

		case DIALOG + 1:
			Builder builder1 = new android.app.AlertDialog.Builder(this);
			// 设置对话框的图标
			builder1.setIcon(R.drawable.buttondraw);
			builder1.setTitle("确定添加新的工程单？");
			builder1.setPositiveButton("确定",
					new android.content.DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							if (TextUtils.isEmpty(type)) {
								Toast.makeText(OrderOtherActivity.this,
										"你还没选择类型！", Toast.LENGTH_LONG).show();
								return;
							}
							boolean b = save();
							if (b) {
								Toast.makeText(OrderOtherActivity.this,
										"添加数据成功", Toast.LENGTH_LONG).show();

							}

						}
					});
			builder1.setNeutralButton("取消",
					new android.content.DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {

						}
					});
			// 创建一个单选按钮对话框
			dialog = builder1.create();
			break;
		}
		return dialog;
	}

	/**
	 * 保存
	 * 
	 * @return
	 */
	public boolean save() {
		boolean b = false;
		ReportDao dao = new ReportDao(this);
		ContentValues values = new ContentValues();
		values.put("ordername", edit1.getEditableText().toString());
		values.put("desc", edit2.getEditableText().toString());
		values.put("soundpath", soundpath);
		values.put("videopath", videopath);
		values.put("status", "0");
		values.put("latitude", latitude);
		values.put("longitude", longitude);

		OrderID = dao.insertReport(values, type);

		if (OrderID > 0) {
			List<ContentValues> lists = new ArrayList<ContentValues>();
			for (int k = 0; k < imagepath.size(); k++) {
				ContentValues value = new ContentValues();
				value.put("otherid", OrderID);
				value.put("status", "1");
				value.put("type", "1");
				value.put("path", imagepath.get(k));

				lists.add(value);
			}
			b = dao.insertALL(lists, DbTableName.RESOURCES);
			dao.close();
		} else {
			return false;
		}

		return b;

	}

	/**
	 * 修改
	 * 
	 * @return
	 */
	public boolean modify() {
		boolean b = false;
		ReportDao dao = new ReportDao(this);
		ContentValues values = new ContentValues();
		values.put("ordername", edit1.getEditableText().toString());
		values.put("desc", edit2.getEditableText().toString());

		values.put("soundpath", soundpath);
		values.put("videopath", videopath);
		values.put("status", "0");
		b = dao.modifyOrder(values, OrderID + "", type);
		if (OrderID > 0) {
			List<ContentValues> lists = new ArrayList<ContentValues>();
			for (int k = 0; k < imagepath.size(); k++) {
				ContentValues value = new ContentValues();
				value.put("otherid", OrderID);
				value.put("status", "1");
				value.put("type", "1");
				value.put("path", imagepath.get(k));

				lists.add(value);
			}
			b = dao.insertALL(lists, DbTableName.RESOURCES);
		}
		dao.close();
		return b;
	}

	/**
	 * 上传更新消息
	 */
	Handler myHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			pd.dismiss();

			if (msg.what == 2) {
				isupload = true;
				Toast.makeText(OrderOtherActivity.this, "上传成功",
						Toast.LENGTH_LONG).show();
				ReportDao dao = new ReportDao(OrderOtherActivity.this);
				dao.delectOrder(OrderID + "");
				boolean b = dao.delectImg(OrderID + "");
				dao.close();
				if (b) {
					OrderID = 0;
				}
			} else {
				Toast.makeText(OrderOtherActivity.this, "上传失败",
						Toast.LENGTH_LONG).show();
			}
		}

	};

	@Override
	protected void onPause() {

		safe = new SafetyExitUtil(OrderOtherActivity.this);
		safe.start();

		super.onPause();
	}

	@Override
	protected void onResume() {
		if (safe != null) {
			safe.stop();
		}
		System.out.println("text onResume ");
		super.onResume();
	}

	/**
	 * 初始化定位
	 */
	public void initlocation() {

		client = new LocationClient(this);
		LocationClientOption option = new LocationClientOption();
		// 打开GPS
		option.setOpenGps(true);

		// 设置坐标类型
		option.setCoorType("bd09ll");

		// 设置网络优先

		option.setPriority(LocationClientOption.GpsFirst);

		// 设置产品线名称
		option.setProdName("waterSys");
		option.disableCache(true);// 禁止启用缓存定位
		// 设置定位定时时间
		option.setScanSpan(10000);
		client.setLocOption(option);
		client.registerLocationListener(this);

	}

	@Override
	public void onReceiveLocation(BDLocation location) {
		GPS(location);
	}

	@Override
	public void onReceivePoi(BDLocation arg0) {

	}

	/**
	 * 得到定位数据
	 * 
	 * @param location
	 */
	public void GPS(BDLocation location) {
		boolean b = openGPSSettings();
		if (!b) {
			return;
		}
		if (location != null) {
			if (location.getLocType() == 61) {
				client.stop();
				pd.setMessage("定位成功");
				pd.dismiss();
				textview2.setText("纬度:" + location.getLatitude());
				textview1.setText("经度：" + location.getLongitude());
				latitude = location.getLatitude();
				longitude = location.getLongitude();
				Toast.makeText(this, "定位成功" + location.getLocType(),
						Toast.LENGTH_LONG).show();
				TipHelper.Vibrate(this, 1000);

				sp.insertValue(XmlNameHelper.GPSLATITUDE,
						location.getLatitude() + "");
				sp.insertValue(XmlNameHelper.GPSLONGITUDE,
						location.getLongitude() + "");
				sp.insertValue(XmlNameHelper.GPSDATE,
						System.currentTimeMillis() + "");
				client.registerLocationListener(this);
			} else {
				client.stop();
				client.registerLocationListener(this);
				pd.dismiss();
				TipHelper.Vibrate(this, 1000);

				Dialog dialog = null;
				String message = "";
				if (sp.getValue(XmlNameHelper.GPSDATE).equals("0")) {
					message = "还没有定位成功过！";
				} else {
					long ti = System.currentTimeMillis()
							- Long.parseLong(sp.getValue(XmlNameHelper.GPSDATE));

					message = "最近一次定位时间在:" + DateUtil.getMuntion(ti);
				}

				Builder builder = new android.app.AlertDialog.Builder(this);
				// 设置对话框的图标
				builder.setIcon(R.drawable.buttondraw);
				// 设置对话框的标题

				builder.setMessage(message);

				// 添加一个确定按钮
				builder.setPositiveButton(" 确 定 ",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								textview2.setText("纬度:"
										+ sp.getValue(XmlNameHelper.GPSLATITUDE));
								textview1.setText("经度："
										+ sp.getValue(XmlNameHelper.GPSLONGITUDE));
								latitude = Double.parseDouble(sp
										.getValue(XmlNameHelper.GPSLATITUDE));
								longitude = Double.parseDouble(sp
										.getValue(XmlNameHelper.GPSLONGITUDE));
								dialog.cancel();
							}
						});
				builder.setNeutralButton("取消",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								textview2.setText("纬度:" + 0.0);
								textview1.setText("经度：" + 0.0);
								latitude = 0.0;
								longitude = 0.0;
								dialog.cancel();
							}
						});
				// 创建一个单选按钮对话框
				dialog = builder.create();
				dialog.show();

			}
		}
	}

	/**
	 * 判断GPS是否存在或开启
	 */
	public boolean openGPSSettings() {
		LocationManager alm = (LocationManager) getSystemService(this.LOCATION_SERVICE);
		if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
			return true;
		}
		Toast.makeText(this, "请开启GPS！", Toast.LENGTH_SHORT).show();
		Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
		startActivityForResult(intent, 0); // 此为设置完成后返回到获取界面
		return false;
	}
}
